package com.wq.concurrency.basic;

/**
 * @Author: wangqiang20995
 * @Date:2019/1/5
 * @Description:
 * @Resource:
 */
public class ThreadJoin {

    private static class JoinTask implements Runnable{

        @Override
        public void run() {
            for(int i = 0;i< 10;i++){
                System.out.println("number-->" + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static class InterruptedTask extends Thread{

        private boolean interrupt = false;

        {
            setName("sub-thread");
        }

        public void interruptCurrentTask(){
            this.interrupt = true;
            System.out.println("call thread:" + Thread.currentThread().getName());
            interrupt();//Interrupted线程，执行结束后不清除线程的中断状态
        }

        @Override
        public void run() {
            try {
                while (!interrupt){
                    System.out.println(System.currentTimeMillis());
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                System.out.println("线程休眠被中断了");
            }


            System.out.println(Thread.currentThread().getState()+ "------end task");
        }


    }


    public static void main(String args[]) throws InterruptedException {
//        joinDemo();
        Thread interrupt = new InterruptedTask();
        interrupt.start();

        Thread.sleep(5000);
        ((InterruptedTask) interrupt).interruptCurrentTask();

        System.out.println("main:join");
        //main线程在这里阻塞，让子线程执行完了main在继续往下走
        interrupt.join();

        System.out.println("all done");
    }

    private static void joinDemo() throws InterruptedException {
        Thread join = new Thread(new JoinTask());
        join.start();

        for(int i = 0;i<100;i++){
            System.out.println("main-->"+i);
            Thread.sleep(10);
        }
        //保证主线程执行完了，加入执行
        join.join();
        System.out.println("end");
    }
}
